﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace IM.Easy.Core.Security
{
    public static class Sha256Hash
    {
        private static readonly string DefaultKey = "default";

        private static string EncryptKey { get; set; } = DefaultKey;

        public static void SetEncryptKey(string encryptKey)
        {
            EncryptKey = encryptKey;
        }

        public static void UseDefaultKey(bool useDefault)
        {
            if (useDefault)
            {
                EncryptKey = DefaultKey;
            }
            else
            {
                EncryptKey = string.Empty;
            }
        }

        public static string ComputeHash(string plainText)
        {
            if (string.IsNullOrEmpty(plainText))
                throw new ArgumentException("加密文本为空", nameof(plainText));

            using SHA256 sha256 = SHA256.Create();
            var txt = plainText + EncryptKey;
            byte[] bytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(txt));
            StringBuilder sb = new StringBuilder();
            foreach (byte b in bytes)
            {
                sb.Append(b.ToString("x2"));
            }
            return sb.ToString();
        }

        public static bool ValidateHash(string plainText, string hash)
        {
            if (string.IsNullOrEmpty(plainText))
                throw new ArgumentException("加密文本为空", nameof(plainText));
            if (string.IsNullOrEmpty(hash))
                throw new ArgumentException("加密文本为空", nameof(hash));

            string computedHash = ComputeHash(plainText);
            return string.Equals(computedHash, hash, StringComparison.OrdinalIgnoreCase);
        }
    }

}
